#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "err.hpp"

const int MSG_BUF_SIZE = 1024;

static struct sockaddr_in tmp;
static socklen_t len;

class UdpClient
{
public:
    UdpClient(std::string svr_ip, uint16_t svr_port)
        : _svr_ip(svr_ip), _svr_port(svr_port)
    {
        // 填充服务器的地址信息
        bzero(&_svr, sizeof(_svr));
        _svr.sin_family = AF_INET;
        _svr.sin_port = htons(_svr_port);
        _svr.sin_addr.s_addr = inet_addr(_svr_ip.c_str());
    }

    void Initial()
    {
        // 1. 创建套接字
        int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (sockfd < 0)
        {
            // 创建套接字失败
            std::cerr << strerror(errno) << std::endl;
            exit(SOCKET_ERR);
        }
        _sockfd = sockfd;

        // 2. 绑定（由操作系统自动绑定，端口号由OS分配）
    }

    // 向服务端发送消息
    void Send(std::string &msg)
    {
        ssize_t n = sendto(_sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr *)&_svr, sizeof(_svr));
        if (n < 0)
        {
            std::cerr << strerror(errno) << std::endl;
            exit(SEND_ERR);
        }
    }

    // 接收服务端发回的消息
    void Recv()
    {
        char msg_buf[MSG_BUF_SIZE];
        memset(msg_buf, 0, MSG_BUF_SIZE);

        int n = recvfrom(_sockfd, msg_buf, sizeof(msg_buf) - 1, 0, (struct sockaddr *)&tmp, &len);
        if (n < 0)
        {
            std::cerr << strerror(errno) << std::endl;
            exit(RECV_ERR);
        }
        msg_buf[n] = '\0';
        std::cout << "[" << inet_ntoa(_svr.sin_addr) << ":" << ntohs(_svr.sin_port) << "] " << std::endl
                  << msg_buf;
    }

private:
    int _sockfd;             // 套接字文件描述符
    std::string _svr_ip;     // 服务器ip
    uint16_t _svr_port;      // 服务器port
    struct sockaddr_in _svr; // 服务器地址信息
};